import { Permission } from "@/models/Permission";
import { Role } from "@/models/Role";
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { In } from "typeorm";
import { z } from "zod";

const roleRoute = new Hono();

roleRoute.get("/", async (c) => {
  let id = c.req.query("id");
  let role = await Role.findOneBy({ id: +id });
  return c.json({ code: 200, message: "获取成功", data: role });
});

roleRoute.get("/list", async (c) => {
  let [list, count] = await Role.findAndCount();
  return c.json({ code: 200, message: "获取成功", data: { list, count } });
});

const addSchema = z.object({
  name: z.string(),
  sort: z.coerce.number(),
});

const updateSchema = z.object({
  id: z.coerce.number(),
  name: z.string(),
  sort: z.coerce.number(),
});

roleRoute.post("/add", async (c) => {
  let body = await c.req.parseBody();

  let result = addSchema.safeParse(body);

  if (!result.success) {
    let message = result.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let role = new Role();
  role.name = result.data.name;
  role.sort = result.data.sort;

  await role.save();

  return c.json({ code: 200, message: "添加成功", data: role });
});

roleRoute.post("/edit", async (c) => {
  let body = await c.req.parseBody();
  let result = updateSchema.safeParse(body);

  if (!result.success) {
    console.log(result.error.issues.map((item) => item.message).join(","));
    let message = result.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let role = await Role.findOneBy({ id: result.data.id });

  if (!role) {
    throw new HTTPException(400, { message: "角色不存在" });
  }

  role.name = result.data.name;
  role.sort = result.data.sort;

  await role.save();

  return c.json({ code: 200, message: "更新成功", data: role });
});

const setPermissionSchema = z.object({
  ids: z.string(),
  roleId: z.coerce.number(),
});

roleRoute.post("/setPermissions", async (c) => {
  let body = await c.req.parseBody();
  let result = setPermissionSchema.safeParse(body);

  if (!result.success) {
    let message = result.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let role = await Role.findOne({
    where: { id: result.data.roleId },
    relations: {
      permissions: true,
    },
  });
  if (!role) {
    throw new HTTPException(400, { message: "角色不存在" });
  }

  let idList = result.data.ids.split(",");

  let permissions = await Permission.find({
    where: {
      id: In(idList),
    },
    relations: {
      roles: true,
    },
  });

  role.permissions = permissions;

  await role.save();

  return c.json({ code: 200, message: "更新成功", data: role });
});

export default roleRoute;
